var redis = require("redis");
var async = require('async');
var config = require('../config')
var logger = require('../logger')

var _client = null;

function connect(cb) {
    //创建redis客户端
    _client = redis.createClient(config.redisPort, config.redisHost);
    //连接错误处理
    _client.on("error", (err) => {
        if (err) {
            cb('redis connect err:' + err);
        }
    });
    _client.select(config.redisUserDatabase, (err) => {
        if (err) {
            cb('redis select database:' + err);
        } else {
            cb(null);
        }
    })
}

function getuser(username, cb) {
    var user = username + config.user;
    _client.get(user, (err, response) => {
        var info = JSON.parse(response);
        cb(err, info);
    })
}

function setuser(username, info, cb) {
    var user = username + config.user;
    var content = JSON.stringify(info);
    _client.set(user, content, (err, response) => {
        cb(err);
    });
}

function deluser(username, cb) {
    var user = username + config.user;
    _client.del(user, (err, response) => {
        cb(err);
    });
}

function queryuser(username, password, cb) {
    getuser(username, (err, response) => {
        if (err) {
            cb(err);
        }
        if (config.debug_login) {
            cb(null);
        } else {
            if (response && response.password == password) {
                cb(null, false);
            }
            else {
                cb('login err');
            }
        }
    })
}

function getalluser(cb){
    _client.smembers(config.alluser,(err,response) => {
        cb(err,response);
    });
}

function adduser(user,cb){
    _client.sadd(config.alluser,user,(err,response) => {
        cb(err);
    });
}

module.exports = {
    connect,
    adduser,
    getuser,
    setuser,
    deluser,
    queryuser,
    getalluser,
}